<!-- 碳排放因子库-碳排放因子库 -->

<template>
  <div>
    <div class="m_contentBox">
      <a-card :bordered="false">
        <div class="m_aCardBox">
          <!-- 搜索框 -->
          <section class="m_cbFlex">
            <section class="searchBoxOutBox" v-click-out="handleBlur">
              <div class="searchBox">
                <input class="searchBox_input" type="text" :placeholder="$t('message.Please_enter')" v-model="queryParam.name"
                       placeholder-class="searchBox_input_placeholder" @focus="handleFocus" @keyup.enter="onSearch()"/>
                <img class="searchBox_clear m_hoverCP" src="@assets/img/img5.png" alt="" @click="onReset"
                     v-if="queryParam.name"/>
                <img class="searchBox_searchIcon m_hoverCP" src="@assets/img/img18.png" alt="" @click="onSearch"/>
              </div>
              <div class="searchRecordsBox" v-if="isShowSearchRecords">
                <div class="searchRecordsBox_header">
                  {{$t('message.History')}}
                  <div class="searchRecordsBox_header_line"></div>
                </div>
                <div v-if="searchRecordsData && searchRecordsData.length > 0">
                  <div class="searchRecordsBox_item m_hoverCP" v-for="(item, index) in searchRecordsData" :key="index"
                       @click="onChangeName(item)">
                    {{ item }}
                  </div>
                </div>
                <div class="searchRecordsBox_noData" v-else>-{{$t('message.No_data')}}-</div>
              </div>
            </section>
            <section class="browseRecordsOutBox" v-click-out="closeIsShowBrowseRecords">
              <div class="browseRecordsBtn m_hoverCP" @click="onChangeIsShowBrowseRecords">{{$t('message.Browse_records')}}</div>
              <div class="browseRecordsBox" v-if="isShowBrowseRecords">
                <div v-if="historyRecordData && historyRecordData.length > 0">
                  <div class="browseRecordsBox_item" :title="item.name || ''" v-for="(item, index) in historyRecordData"
                       :key="index">
                    <div class="browseRecordsBox_item_text m_hoverCP" @click="onDetail({id:item.id})">
                      <div class="browseRecordsBox_item_text1 m_pass_1line_hidden">
                        {{ item.name }}
                      </div>
                      <div class="browseRecordsBox_item_text2 m_pass_1line_hidden">
                        {{ (Number(item.factorValue)).toFixed(4) }}
                        {{ item.numeratorUnit }}/
                        {{ item.denominatorUnit }}
                      </div>
                    </div>
                    <div class="m_cFlex">
                      <img class="browseRecordsBox_item_copyIcon m_hoverCP" src="@assets/img/img25.png" alt=""
                           @click="onCopy(item, index)"/>
                      <img class="browseRecordsBox_item_collectIcon m_hoverCP" src="@assets/img/img11.png" alt=""
                           @click="onCollect(item, index)"
                           v-if="item.collectStatus === '1' && item.type == 1"/>
                      <img class="browseRecordsBox_item_collectIcon m_hoverCP" src="@assets/img/img12.png" alt=""
                           @click="onCollect(item, index)"
                           v-if="item.collectStatus === '0' && item.type == 1"/>
                      <img class="browseRecordsBox_item_collectIcon" src="@assets/img/img12.png" alt=""
                           style="opacity: 0;" v-if="item.type == 2"/>
                    </div>
                  </div>
                </div>
                <div class="browseRecordsBox_noData" v-else>
                  <img class="browseRecordsBox_noData_img" src="@assets/img/img26.png" alt=""/>
                  <div class="browseRecordsBox_noData_text">-{{$t('message.No_data')}}-</div>
                </div>
              </div>
            </section>
          </section>
          <!-- 相关行业筛选 -->
          <section class="screenBox">
            <div class="screenBox_box1">
              <div class="screenBox_box1_label"> {{$t('message.Related_industries')}}：</div>
              <div class="screenBox_box1_content">
                <div class="screenBox_box1_content_item m_hoverCP"
                     :class="{ 'screenBox_box1_content_item_active': queryParam.industryId === item.id || !queryParam.industryId && !item.id && searched }"
                     v-for="(item, index) in industryData" :key="item.id" @click="onChangeScreenKey(item)">
                  {{ item.name }}<span v-if="showNum">({{ item.totalNum || 0 }})</span>
                </div>
              </div>
            </div>
          </section>
          <section>
            <section class="searchContent" v-if="openListData && openListData.length > 0">
              <div style="width: 100%">

                <div class="cardList">
                  <div class="cardItem" v-for="(item, index)  in openListData" :key="index"
                       @click="onDetail(item)">
                    <yzCard :item="item" @change="getData"></yzCard>
                  </div>
                </div>
                <a-pagination show-size-changer show-quick-jumper v-model="pageObj.pageNo"
                              :page-size="pageObj.pageSize" :total="pageObj.total"
                              :page-size-options="pageObj.pageSizeOptions"
                              :show-total="(total, range) => range[0] + '-' + range[1] + ' 共' + total + '条'"
                              style="margin: 24px auto 0;width: fit-content;"
                              @change="onChangePage" @showSizeChange="onChangePageSize">
                  <template slot="buildOptionText" slot-scope="props">
                    <span>{{ props.value }}条/页</span>
                  </template>
                </a-pagination>
              </div>
            </section>
            <section class="searchContent" v-else>
              <emptyBox :text1="$t('message.Sorry__there_are_no_relevant_search_results')"
                :text2="$t('message.Welcome_to_contact_us_and_make_suggestions')"
                :btnText="$t('message.Contact_us')"
                @change="onConcat"></emptyBox>
            </section>
          </section>
        </div>
      </a-card>
    </div>
    <section class="m_popupBox" v-if="isShowDetailPopup">
      <tpyzDetail ref="tpyzDetail" @back="back"></tpyzDetail>
    </section>
  </div>

</template>

<script>
import Vue from 'vue'
import {ACCESS_TOKEN, TENANT_ID} from "@/store/mutation-types"
import {deleteAction, getAction, postAction} from '@/api/manage'
import emptyBox from '@comp/common/emptyBox.vue'
import yzCard from '@comp/common/yzCard.vue'
import tpyzDetail from '@views/module_emission/tpfyzkView/modules/tpyzDetail.vue'
import {INDUSTRY} from "@/common/constKey";
import {copyText} from "@/utils/util";
import {
  get_TPYZ_SearchRecords,
  remove_TPYZ_SearchRecords,
  set_TPYZ_SearchRecords
} from "@/common/storage";

export default {
  name: 'tpfyzkView',
  components: {
    emptyBox,
    yzCard,
    tpyzDetail,
  },
  data() {
    return {
      token: Vue.ls.get(ACCESS_TOKEN),
      // 查询请求数据
      queryParam: {
        type: 1, // 类型（1=碳排因子库，2=组织因子库）
        token: Vue.ls.get(ACCESS_TOKEN),
      },
      pageObj: {
        pageNo: 1,
        pageSize: 12,
        total: 0,
        pageSizeOptions: ['12', '24', '36', '48', '60'],
      },
      isShowSearchRecords: false, // 是否显示搜索记录
      searchRecordsData: [], // 搜索历史纪录数据
      isShowBrowseRecords: false, // 是否显示浏览记录
      historyRecordData: [], // 浏览记录数据
      isShowDetailPopup: false, // 详情弹窗状态
      categoryChildList: [], // 分类字典-查询行业分类
      topSearchFactorData: [], // 热门搜索因子数据
      newPublishFactorData: [], // 最新发布因子数据
      openListData: [], // 碳排因子-分页列表查询
      IndustryTypeBadgeData: [], // 碳排因子-统计数
      industryData: [], // 行业数据
      searched: false, // 是否是筛选状态
      showNum: false, // 是否展示行业上的统计数据
    };
  },
  watch: {
    $route: {
      handler: function(newRoute, oldRoute){
        this.onSearch();
      },
    }
  },
  created() {
    this.searchRecordsData = get_TPYZ_SearchRecords() || []
    console.log('searchRecordsData', this.searchRecordsData)
    this.getData()
    this.searched = true
    this.queryParam.industryId = ''
    //获取路由参数
    console.log('queryParam', this.$route.path)
    //切割等号后面的数据
    this.onSearch()
  },
  methods: {
    /**
     * 修改页码
     */
    onChangePage(page, pageSize) {
      console.log('onChangePage', page, pageSize);
      this.pageObj.pageNo = page
      this.onSearch();
    },
    /**
     * 修改每页条数
     */
    onChangePageSize(current, size) {
      console.log('onChangePageSize', current, size);
      this.pageObj.pageNo = 1
      this.pageObj.pageSize = size
      this.onSearch();
    },
    /**
     * 选择搜索历史记录
     */
    onChangeName(item) {
      console.log('onChangeName', item)
      this.queryParam.name = item
      this.handleBlur()
      this.onSearch()
    },
    /**
     * 显示搜索历史记录
     */
    handleFocus() {
      this.isShowSearchRecords = !this.isShowSearchRecords
    },
    /**
     * 隐藏搜索历史记录
     */
    handleBlur() {
      this.isShowSearchRecords = false
    },
    /**
     * 因子详情
     */
    onDetail(item) {
      if (!this.token) {
        this.$message.warning(this.$t('message.Please_log_in'))
        this.$router.push('/user/login');
        return
      }
      this.isShowDetailPopup = true
      this.$nextTick(() => {
        console.log('onDetail', this.$refs)
        this.$refs.tpyzDetail.detailIndex = 0
        this.$refs.tpyzDetail.detailKeys = [item.id]
        this.$refs.tpyzDetail.getData()
      })
    },
    /**
     * 显示/隐藏浏览记录
     */
    onChangeIsShowBrowseRecords() {
      this.isShowBrowseRecords = !this.isShowBrowseRecords
    },
    /**
     * 隐藏浏览记录
     */
    closeIsShowBrowseRecords() {
      console.log('closeIsShowBrowseRecords')
      this.isShowBrowseRecords = false
    },
    back() {
      this.isShowDetailPopup = false
      this.getData()
    },
    /**
     * 联系
     */
    onConcat() {
      console.log('onConcat');
      this.$message.success(this.$t('message.Contact_us'))
    },
    onSearch() {
      // 筛选因子
      // 关闭搜索历史记录
      this.isShowSearchRecords = false
      if (this.queryParam.name) {
        // 记录搜索记录历史
        // console.log('set_TPYZ_SearchRecords 1', this.searchRecordsData)
        let theIndex = this.searchRecordsData.findIndex(ele => ele == this.queryParam.name)
        // 重复的删除
        if (theIndex > -1) {
          this.searchRecordsData.splice(theIndex, 1)
        }
        // 记录最新的一条
        this.searchRecordsData.unshift(this.queryParam.name)
        // 最多记录5条
        if (this.searchRecordsData.length > 5) {
          this.searchRecordsData = this.searchRecordsData.slice(0, 5)
        }
        set_TPYZ_SearchRecords(this.searchRecordsData)
        // console.log('set_TPYZ_SearchRecords 2', this.searchRecordsData)
      }
      this.searched = true
      this.queryParam.pageNo = this.pageObj.pageNo
      this.queryParam.pageSize = this.pageObj.pageSize
      this.queryParam.state = 1 // 用于区分：碳排因子库-碳排因子库、管理平台-碳排因子库
      this.queryParam.emissionFactorDatabase = this.$route.path.split('=')[1] || '1'
      getAction('/emission/factor/cyEmissionFactor/list', this.queryParam).then((res) => {
        if (res.success) {
          this.openListData = res.result.records || []
          this.pageObj.total = res.result.total
          if (this.queryParam.name) {
            this.showNum = true
            if (!this.queryParam.industryId) {
              this.IndustryTypeBadge()
            }
          } else {
            this.showNum = false
          }
        }
      });
    },
    /**
     * 获取行业统计数量
     */
    IndustryTypeBadge() {
      getAction('/emission/factor/cyEmissionFactor/IndustryTypeBadge').then((res) => {
        if (res.success) {
          this.IndustryTypeBadgeData = res.result || {}
          // 其他行业
          this.industryData.forEach(item => {
            this.$set(item, 'totalNum', 0)
            for (const [key, value] of Object.entries(this.IndustryTypeBadgeData)) {
              if (item.id == key) {
                this.$set(item, 'totalNum', value)
              }
            }
          })
          // 全行业
          let total = 0
          for (const [key, value] of Object.entries(this.IndustryTypeBadgeData)) {
            total = total + value
          }
          this.industryData[0].totalNum = total
          console.log('industryData', this.industryData)
        }
      });
    },
    onReset() {
      delete this.queryParam.name
      delete this.queryParam.industryId
      this.onSearch()
    },
    getData() {
      // 行业
      if (this.token) {
        // 登录
        getAction('/sys/category/childList', {
          pid: INDUSTRY
        }).then((res) => {
          if (res.success) {
            let industryData = [{
              name: this.$t('message.whole_industry'),
              id: ''
            }]
            this.industryData = industryData.concat(res.result || [])
          }
        });
        // 浏览记录数据
        getAction('/emission/factor/cyEmissionFactor/historyRecord').then((res) => {
          if (res.success) {
            this.historyRecordData = res.result || []
          }
        });
      } else {
        // 未登录
        getAction('/emission/factor/cyEmissionFactor/industryCategory').then((res) => {
          if (res.success) {
            let industryData = [{
              name: this.$t('message.whole_industry'),
              id: ''
            }]
            this.industryData = industryData.concat(res.result || [])
          }
        });
      }
      if (this.searched) {
        // 筛选状态
        this.onSearch()
      } else {
        // 非筛选状态
        // 热门搜索因子
        getAction('/emission/factor/cyEmissionFactor/topSearchFactor', {
          SearchNum: 8,
          token: Vue.ls.get(ACCESS_TOKEN),
        }).then((res) => {
          if (res.success) {
            this.topSearchFactorData = res.result || []
          }
        });
        // 最新发布因子
        getAction('/emission/factor/cyEmissionFactor/newPublishFactor', {
          Number: 4,
          token: Vue.ls.get(ACCESS_TOKEN),
        }).then((res) => {
          if (res.success) {
            this.newPublishFactorData = res.result || []
          }
        });
      }
    },
    /**
     * 相关行业筛选-切换
     */
    onChangeScreenKey(item) {
      this.queryParam.industryId = item.id
      this.onSearch()
    },
    /**
     * 浏览记录-复制
     */
    onCopy(item, index) {
      let copyMsg = `${item.name} ${item.factorValue} ${item.numeratorUnit}/${item.denominatorUnit}`
      copyText(copyMsg)
    },
    /**
     * 浏览记录-收藏
     */
    onCollect(item, index) {
      if (item.collectStatus === '1') {
        // 取消收藏
        deleteAction('/CyEmissionFactorCollect/cyEmissionFactorCollect/delete', {
          id: item.id,
        }).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('message.delete_collect_success'))
            this.getData()
          }
        });
      } else if (item.collectStatus === '0') {
        // 收藏
        getAction('/CyEmissionFactorCollect/cyEmissionFactorCollect/add', {
          id: item.id,
        }).then((res) => {
          if (res.success) {
            this.$message.success(this.$t('message.collect_success'))
            this.getData()
          }
        });
      }
    },
  },
};

</script>

<style lang="less" scoped>
/deep/ .ant-card-body {
  background: #F5F8F7;
}

.searchContent {
  margin-top: 24px;
  padding: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #FFFFFF;
  border-radius: 3px;
}


.searchBoxOutBox {
  position: relative;

  .searchBox {
    padding: 0 4px 0 8px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 372px;
    height: 32px;
    background: #FFFFFF;
    box-shadow: 2px 2px 0px 0px rgba(20, 137, 88, 0.08);
    border-radius: 3px;
    border: 1px solid #148958;

    .searchBox_input {
      width: 300px;
      height: 22px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
      line-height: 22px;
      border: none;
      outline: none;
    }

    .searchBox_input_placeholder {
      color: rgba(0, 0, 0, 0.4);
    }

    .searchBox_clear {
      width: 16px;
      height: 16px;
    }

    .searchBox_searchIcon {
      width: 24px;
      height: 24px;
    }
  }

  .searchRecordsBox {
    position: absolute;
    z-index: 3;
    top: 40px;
    left: 0;
    padding: 6px 13px 0;
    width: 372px;
    background: #FFFFFF;
    box-shadow: 0px 2px 4px -1px rgba(0, 0, 0, 0.12), 0px 4px 5px 0px rgba(0, 0, 0, 0.08), 0px 1px 10px 0px rgba(0, 0, 0, 0.05);
    border-radius: 6px;
  }

  .searchRecordsBox_header {
    margin-bottom: 5px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: rgba(0, 0, 0, 0.4);
  }

  .searchRecordsBox_header_line {
    flex: 1;
    height: 1px;
    background: #E7E7E7;
  }

  .searchRecordsBox_noData {
    margin-bottom: 10px;
    text-align: center;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #888888;
  }

  .searchRecordsBox_item {
    margin-bottom: 10px;
    width: 346px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: rgba(0, 0, 0, 0.9);
  }

  .searchRecordsBox_item:hover {
    background: #E3F9E9;
  }
}


.browseRecordsOutBox {
  position: relative;

  .browseRecordsBtn {
    display: flex;
    align-items: center;
    justify-content: center;
    // width: 80px;
    padding: 0 5px;
    height: 24px;
    background: #FFFFFF;
    border-radius: 2px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #333333;
  }

  .browseRecordsBox {
    position: absolute;
    z-index: 3;
    top: 32px;
    right: 0;
    padding: 12px;
    background: #FFFFFF;
    box-shadow: 4px 4px 12px 0px rgba(0, 0, 0, 0.07);
    border-radius: 3px;

    .browseRecordsBox_noData {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 251px;
      height: 172px;
      //background: #FFFFFF;
      //box-shadow: 4px 4px 12px 0px rgba(0,0,0,0.07);
      //border-radius: 3px ;

      .browseRecordsBox_noData_img {
        display: block;
        width: 62px;
        height: 62px;
      }

      .browseRecordsBox_noData_text {
        margin-top: 7px;
        text-align: center;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        font-size: 12px;
        color: #888888;
      }
    }

    .browseRecordsBox_item {
      margin-bottom: 14px;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .browseRecordsBox_item:last-child {
      margin-bottom: 0;
    }

    .browseRecordsBox_item_text {
      width: 250px;
      display: flex;
    }

    .browseRecordsBox_item_text1 {
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 14px;
      color: #333333;
      //==========================
      max-width: 100px;
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-wrap: break-word;
      word-break: break-all;
    }

    .browseRecordsBox_item_text2 {
      margin-left: 4px;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      font-size: 12px;
      color: #148958;
      line-height: 22px;
      //==========================
      max-width: 150px;
      display: block;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      word-wrap: break-word;
      word-break: break-all;
    }

    .browseRecordsBox_item_copyIcon {
      margin-left: 3px;
      width: 18px;
      height: 18px;
    }

    .browseRecordsBox_item_collectIcon {
      margin-left: 7px;
      width: 18px;
      height: 18px;
    }
  }
}

.screenBox {
  margin-top: 25px;
  padding: 26px 16px;
  background: #FFFFFF;
  border-radius: 3px;

  .screenBox_box1 {
    display: flex;
    align-items: flex-start;
  }

  .screenBox_box1_label {
    // width: 70px;
    height: 20px;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 14px;
    color: #333333;
    line-height: 16px;
    transform: translateY(4px);
  }

  .screenBox_box1_content {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .screenBox_box1_content_item {
    display: flex;
    align-items: center;
    padding: 0 16px;
    height: 24px;
    background: #FFFFFF;
    border-radius: 2px;
    border: 1px solid #CDCDCD;
    font-family: PingFang SC, PingFang SC;
    font-weight: 400;
    font-size: 12px;
    color: #333333;

    img {
      margin-left: 4px;
      width: 10px;
      height: 10px;
    }
  }

  .screenBox_box1_content_item_active {
    border-color: #148958;
    color: #148958;

  }
}

.list_card {
  margin-top: 25px;
  background: #FFFFFF;
  border-radius: 3px;
  padding: 17px 25px 25px;

  .list_card_title {
    display: flex;
    align-items: center;
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 16px;
    color: #333333;

    img {
      margin-right: 8px;
      width: 22px;
      height: 22px;
    }
  }
}

.cardList {
  width: 100%;
  gap: 20px;
  display: grid;
  // grid-template-columns: repeat(4, 1fr);
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));

  .cardItem {

  }
}
</style>
